__author__ = 'Lenka'

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import *
from selenium.webdriver.common.by import By

from php4dvd.pages.loginpage import LoginPage
from php4dvd.pages.internalpage import InternalPage
from php4dvd.pages.userprofilepage import UserProfilePage
from php4dvd.model.user import User


class Application(object):
    """
    This class describes the logic of application.
    """

    def __init__(self, driver, base_url):
        driver.get(base_url)
        self.wait = WebDriverWait(driver, 10)
        self.lp = LoginPage(driver, base_url)
        self.ip = InternalPage(driver, base_url)
        self.upp = UserProfilePage(driver, base_url)

    def login(self, user):
        self.lp.username_field.clear()
        self.lp.username_field.send_keys(user.username)
        self.lp.password_field.clear()
        self.lp.password_field.send_keys(user.password)
        self.lp.submit_button.click()

    def logout(self):
        self.ip.logout_button.click()
        self.wait.until(alert_is_present()).accept()

    def is_logged_in(self):
        return self.ip.is_this_page

    def is_not_logged_in(self):
        return self.lp.is_this_page

    def is_logged_in_as(self, user):
        return self.is_logged_in() and self.get_logged_user().username == user.username

    def get_logged_user(self):
        self.ip.user_profile_link.click()
        self.upp.is_this_page
        return User(username=self.upp.username_field.get_attribute("value"),
                    email=self.upp.email_field.get_attribute("value"))

    def ensure_login_as(self, user):
        element = self.wait.until(presence_of_element_located((By.CSS_SELECTOR, "nav, #loginform")))
        if element.tag_name == 'nav':
            if self.is_logged_in_as(user):
                return
            else:
                self.logout()
        self.login(user)

    def ensure_logout(self):
        element = self.wait.until(presence_of_element_located((By.CSS_SELECTOR, "nav, #loginform")))
        if element.tag_name == 'nav':
            self.logout()



